#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include "server.h"

int chat_to(int sock_fd)
{
	int tmp;
	char from[NAME_LEN_MAX + 1];
	char to[NAME_LEN_MAX + 1];
	char msg[MSG_LEN_MAX + 1];

	recv(sock_fd, &tmp, sizeof(int), 0);
	memset(from, 0, NAME_LEN_MAX + 1);
	recv(sock_fd, from, tmp, 0);
	
	recv(sock_fd, &tmp, sizeof(int), 0);
	memset(to, 0, NAME_LEN_MAX + 1);
	recv(sock_fd, to, tmp, 0);
	
	recv(sock_fd, &tmp, sizeof(int), 0);
	memset(msg, 0, MSG_LEN_MAX + 1);
	recv(sock_fd, msg, tmp, 0);

	int i;
	user *u = get_user(to);
	if ( ( u == NULL) || ( u->sock_fd == -1) )
	{
		tmp = -1;
		send(sock_fd, &tmp, sizeof(int), 0);
	}
	else
	{
		tmp = strlen(from);
		send(u->sock_fd2, &tmp, sizeof(int), 0);
		send(u->sock_fd2, from, tmp, 0);
		tmp = strlen(msg);
		send(u->sock_fd2, &tmp, sizeof(int), 0);
		send(u->sock_fd2, msg, tmp, 0);
		tmp = 0;
		send(sock_fd, &tmp, sizeof(int), 0);
	}
	printf("chat_to:\t%d\n", tmp);
}
